//
//  BELayerExtension.swift
//  BasicExtensions
//
//  Created by 范晓鑫 on 2023/3/30.
//

import UIKit

public protocol BETransactionDisable: AnyObject {}

@dynamicMemberLookup
public struct BETransactionDisabled<Layer: BETransactionDisable> {
    let base: Layer
    
    public subscript<ValueType>(dynamicMember keyPath: ReferenceWritableKeyPath<Layer, ValueType>) -> ValueType {
        get {
            return base[keyPath: keyPath]
        }
        nonmutating set {
            CATransaction.begin()
            CATransaction.setDisableActions(true)
            base[keyPath: keyPath] = newValue
            CATransaction.commit()
        }
    }
}

extension BETransactionDisable {
    /// 不要做动画，默认设置CALayer的属性会自动添加动画，使用该扩展可以不使用动画来设置属性
    public var dontAnimate: BETransactionDisabled<Self> {
        return .init(base: self)
    }
}

extension CALayer: BETransactionDisable {}

extension CALayer {
    /// 模仿UIView的performWithoutAnimation，因为CALayer设置属性会自带动画，需要去掉动画的时候使用该方法包裹
    class func performWithoutAnimation(_ actionsWithoutAnimation: () -> Void) {
        CATransaction.begin()
        CATransaction.setDisableActions(true)
        actionsWithoutAnimation()
        CATransaction.commit()
    }
}
